const router = require('koa-router')();
const DB = require('../../module/db.js');

router.get('/', async (ctx) => {

    await ctx.render('admin/index');
});


// 封装状态改变
router.get('/changeStatus', async (ctx) => {

	let collectionName = ctx.query.collectionName;
	let attr = ctx.query.attr;
	let id = ctx.query.id;
	
	let result = await DB.findOne(collectionName, {
		_id: DB.getObjectID(id)
	});
	
	if(result.length <= 0) {
		ctx.body = {
			message: '更新失败，无法获取对应数据', 
			success: false
		}
		return;
	}
	
	let json = {
		[attr]: (result[0][attr] === 1) ? 0 : 1
	};
		
	let updateResult = await DB.updateOne(collectionName, {
		_id: DB.getObjectID(id)
	}, json);
	
	ctx.body = (updateResult) ? {message: '更新成功', success: true} : {message: '更新失败', success: false};
});

// 封装删除
router.get('/delete', async (ctx) => {
	
	try {
		let collectionName = ctx.query.collectionName;
		let id = ctx.query.id;
		
		let result = await DB.deleteOne(collectionName, {
			_id: DB.getObjectID(id)
		});
	} catch (err) {
		console.log(err);
	} finally {
		ctx.redirect(ctx.state.G.referer);
	}
});

// 封装排序
router.get('/changeSort', async(ctx) => {
	let collectionName = ctx.query.collectionName;
	let id = ctx.query.id;
	let sort = (ctx.query.value) ? parseInt(ctx.query.value, 0) : 0;

	let result = await DB.updateOne(collectionName, {
		_id: DB.getObjectID(id)
	}, {
		sort: sort
	});

	if(result) {
		ctx.body = {
			message: '更新成功',
			success: true
		}
	}else {
		ctx.body = {
			message: '更新失败',
			success: false
		}
	}
});


module.exports = router.routes();